using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Shared.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace UniversalAdmin.Application.Services;

public class PermissionService : IPermissionService
{
    private readonly IPermissionRepository _permissionRepository;

    public PermissionService(IPermissionRepository permissionRepository)
    {
        _permissionRepository = permissionRepository;
    }

    // 获取所有权限
    public async Task<IEnumerable<PermissionDto>> GetAllPermissionsAsync()
    {
        try
        {
            var permissions = await _permissionRepository.GetAllAsync();

            var result = permissions.Select(p => new PermissionDto(
                p.Id,
                p.Name,
                p.Description,
                p.Resource,
                p.Action,
                p.Type,
                p.SortOrder,
                p.IsEnabled
            )).ToList();

            return result;
        }
        catch (Exception)
        {
            throw;
        }
    }

    // 根据ID获取权限
    public async Task<PermissionDto?> GetPermissionByIdAsync(Guid id)
    {
        var permission = await _permissionRepository.GetByIdAsync(id);

        if (permission == null)
            return null;

        return new PermissionDto(
            permission.Id,
            permission.Name,
            permission.Description,
            permission.Resource,
            permission.Action,
            permission.Type,
            permission.SortOrder,
            permission.IsEnabled
        );
    }

    // 创建权限
    public async Task<PermissionDto> CreatePermissionAsync(CreatePermissionDto dto)
    {
        var permission = new Permission
        {
            Name = dto.Name,
            Description = dto.Description,
            Resource = dto.Resource,
            Action = dto.Action,
            Type = dto.Type,
            SortOrder = dto.SortOrder,
            IsEnabled = dto.IsEnabled
        };

        await _permissionRepository.AddAsync(permission);
        await _permissionRepository.SaveChangesAsync();

        return new PermissionDto(
            permission.Id,
            permission.Name,
            permission.Description,
            permission.Resource,
            permission.Action,
            permission.Type,
            permission.SortOrder,
            permission.IsEnabled
        );
    }

    // 更新权限
    public async Task<PermissionDto?> UpdatePermissionAsync(Guid id, UpdatePermissionDto dto)
    {
        var permission = await _permissionRepository.GetByIdAsync(id);

        if (permission == null)
            return null;

        permission.Name = dto.Name;
        permission.Description = dto.Description;
        permission.Resource = dto.Resource;
        permission.Action = dto.Action;
        permission.Type = dto.Type;
        permission.SortOrder = dto.SortOrder;
        permission.IsEnabled = dto.IsEnabled;

        await _permissionRepository.UpdateAsync(permission);
        await _permissionRepository.SaveChangesAsync();

        return new PermissionDto(
            permission.Id,
            permission.Name,
            permission.Description,
            permission.Resource,
            permission.Action,
            permission.Type,
            permission.SortOrder,
            permission.IsEnabled
        );
    }

    // 删除权限
    public async Task<bool> DeletePermissionAsync(Guid id)
    {
        var permission = await _permissionRepository.GetByIdAsync(id);

        if (permission == null)
            return false;

        // 检查是否被角色使用
        var isUsedByRoles = await _permissionRepository.IsUsedByRolesAsync(id);
        if (isUsedByRoles)
        {
            throw new InvalidOperationException("无法删除已被角色使用的权限项");
        }

        await _permissionRepository.DeleteAsync(permission);
        await _permissionRepository.SaveChangesAsync();

        return true;
    }

    // 获取权限树（简化为平铺列表）
    public async Task<IEnumerable<PermissionTreeDto>> GetPermissionTreeAsync()
    {
        try
        {
            var permissions = await _permissionRepository.GetPermissionTreeAsync();

            return permissions.Select(p => new PermissionTreeDto(
                p.Id,
                p.Name,
                p.Description,
                p.Resource,
                p.Action,
                p.Type,
                p.SortOrder,
                p.IsEnabled
            ));
        }
        catch (Exception)
        {
            // 记录错误并返回空列表
            return new List<PermissionTreeDto>();
        }
    }

    // 根据角色获取权限
    public async Task<IEnumerable<PermissionDto>> GetPermissionsByRoleAsync(Guid roleId)
    {
        var permissions = await _permissionRepository.GetByRoleIdAsync(roleId);

        return permissions.Select(p => new PermissionDto(
            p.Id,
            p.Name,
            p.Description,
            p.Resource,
            p.Action,
            p.Type,
            p.SortOrder,
            p.IsEnabled
        ));
    }

    // 批量更新权限状态
    public async Task BatchUpdateStatusAsync(List<Guid> permissionIds, bool isEnabled)
    {
        await _permissionRepository.BatchUpdateStatusAsync(permissionIds, isEnabled);
    }

    // 获取权限统计信息
    public async Task<object> GetPermissionStatsAsync()
    {
        return await _permissionRepository.GetPermissionStatsAsync();
    }
}